const { query, connect } = require('../model/index');
const callingCardModel = require('../model/callingCard');
const { objectAttrHas } = require('../common/utils');

/**
 * 名片列表
 * @param {*} queryParams 
 * @param {*} param1 
 * @returns 
 */
const callingCardList = async (queryParams, { pageNum, pageSize }) => {
  const whereArr = [];

  for (let key in queryParams) {
    if (['status'].includes(key)) {
      continue;
    }
    if (queryParams[key] != '' && queryParams[key] != null) {
      if (key == 'category') {
        whereArr.push(`FIND_IN_SET('${queryParams[key]}',${key})`);
      } else if (['name', 'title'].includes(key)) {
        whereArr.push(`${key} like '%${queryParams[key]}%'`);
      } else {
        whereArr.push(`${key} = '${queryParams[key]}'`);
      }
    }
  }
  
  let statusVal;
  if (objectAttrHas(queryParams, 'status') && queryParams['status'] instanceof Array) {
    statusVal = queryParams['status'];
  } else {
    statusVal = [1];
  }

  const whereAnd = whereArr.length > 0 ? whereArr.join(' and ') + ' and' : '';

  const database = callingCardModel.TABLE_NAME;
  let [rows, fields] = await connect.query(
    `select * from ${database} where ${whereAnd} status in (?) order by id desc limit ? offset ?`,
    [statusVal, pageSize, pageNum * pageSize]
  );
  let [countRows] = await connect.query(
    `select count(*) as count from ${database} where ${whereAnd} status in (?)`,
    [statusVal]
  );
  const total = countRows[0].count || 0;
  const pageCount = Math.ceil(total / pageSize); // 总页数

  return {
    pageCount,
    list: rows,
    total
  }
};

module.exports = {
  callingCardList
}